package servlet;

import com.alibaba.fastjson.JSON;
import entity.User;
import service.*;
import service.impl.RedisServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/verify")
public class VerifyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        UserService userService = new UserServiceImpl();
        User user = null;
        // 获取手机号码
        String phone  = request.getParameter("phone");

        // 创建SmsService
        SmsService smsService = new SmsServiceImpl();

        // 创建RedisService
        RedisService redisService = new RedisServiceImpl();

        Long ttl = redisService.ttl(phone);

        // 保存code到redis
        Map map = new HashMap();

        try {
            user = userService.phones(phone);
        } catch (SQLException e) {
            e.printStackTrace();
        }
            if (ttl != null && ttl.longValue() < 240) {
                // 获取随机数
                String code = String.valueOf(Math.random()).substring(2, 8);
                boolean sended = false;
                try {
                    // 调用发短信的服务
                    sended = true;//smsService.sendMsg(phone,"1",code,"5");
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                if (sended) {
                    boolean saved = redisService.setEx(phone, code, 5 * 60);
                    if(user != null){
                        map.put("sended", 2);
                    }else if (saved) {
                        map.put("sended", true);
                    } else {
                        map.put("sended", false );
                    }
                }
            } else {
                map.put("canSend", false);
                map.put("ttl", 60 - (300 - ttl));
            }
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(map));
        // 刷新并关闭
        out.flush();
        out.close();
    }
}
